package chargement;


import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class RepositoryT<T> {
	public File base;
	private List<Class<? extends T>> l;
	private MyClassLoader mcl;
	private Class<T> superClass;

	public RepositoryT(File base, Class<T> superClass) {
		mcl = new MyClassLoader(base);
		this.base = base;
		this.superClass = superClass;

	}

	public List<Class<? extends T>> load() {
		l = new ArrayList<Class<? extends T>>();
		try {
			load(base, null);
		} catch (ClassNotFoundException ex) {
			Logger.getLogger(Repository.class.getName()).log(Level.SEVERE, null, ex);
		}
		return l;
	}

	private void load(File f, String chemin) throws ClassNotFoundException {
		for (File f1 : f.listFiles()) {
			if (f1.isDirectory()) {
				if (chemin == null)
					chemin = f1.getName();
				else
					chemin = chemin + "." + f1.getName();
				this.load(f1, chemin);
			} else if (f1.getName().endsWith(".class")) {
				Class<?> c;
				if (chemin == null) {
					String maChaine = f1.getName();
					maChaine = maChaine.substring(0, (maChaine.length() - 6));
					c = mcl.loadClass(maChaine);
				} else {
					String maChaine = chemin + "." + f1.getName();
					maChaine = maChaine.substring(0, (maChaine.length() - 6));
					c = mcl.loadClass(maChaine);
				}
				if (superClass.isAssignableFrom(c)) {
					l.add(c.asSubclass(superClass));
				}
			}
		}
	}
}